const crypto = require("crypto");
const dict_arr = [
  {
    dict_key: "post",
    dict_value: "厨师岗位",
    dict_type: "business",
    description: "厨师岗位",
  },
  {
    dict_key: "years_of_service",
    dict_value: "工作年限",
    dict_type: "business",
    description: "工作年限",
  },
  {
    dict_key: "article_type",
    dict_value: "文章类型",
    dict_type: "system",
    description: "文章类型",
  },
  {
    dict_key: "help_question_category",
    dict_value: "帮助中心分类",
    dict_type: "business",
    description: "帮助中心分类",
  },
  {
    dict_key: "ad_category",
    dict_value: "广告类型",
    dict_type: "business",
    description: "广告类型",
  },
  {
    dict_key: "cuisine",
    dict_value: "菜系分类",
    dict_type: "business",
    description: "菜系分类",
  },
  {
    dict_key: "work_experience",
    dict_value: "工作经验",
    dict_type: "business",
    description: "工作经验",
  },
];
// 业务类型  'business','system'
async function dict_init(app) {
  for (let item of dict_arr) {
    let dict = await app.model.Dictionary.findOne({
      where: { dict_key: item.dict_key },
    });
    if (!dict) await app.model.Dictionary.create(item);
  }
  app.logger.info("[egg-Redis] 数据库字典表初始化完成");
}

async function user_init(app) {
  const body = {
    phone: "153091776842",
    password: "123456",
    user_type: "admin", // 角色类型：admin-管理员
    status: 1, // 状态：1-正常
    avatar: "https://example.com/default-avatar.png", // 默认头像
    created_at: new Date(),
    updated_at: new Date(),
  };
  // 检查是否存在管理员账号
  const adminUser = await app.model.User.findOne({
    where: {
      phone: body.phone,
      user_type: body.user_type,
    },
  });

  // 如果不存在管理员账号，则创建
  if (!adminUser) {
    // 使用MD5加密密码
    body.password = crypto
      .createHash("md5")
      .update(body.password)
      .digest("hex");

    await app.model.User.create(body);

    app.logger.info("[egg-admin] 管理员账号初始化成功");
  } else if (adminUser.status === 0) {
    // 如果管理员账号存在但被禁用，则重新启用
    await adminUser.update({
      status: 1,
      updated_at: new Date(),
    });
    app.logger.info("[egg-admin] 管理员账号已重新启用");
  }
}

async function redis_set_ads(app) {
  // 获取所有有效的广告数据
  const ads = await app.model.Ads.findAll(
      {
        where: { status: 1,del_flag:0 },
        attributes:{exclude:['updated_at','status','del_flag']},
        order:[['created_at','DESC']]
      }
  );
  // 如果不存在则新增数据
  await app.redis.set("ads_list", JSON.stringify(ads));
  app.logger.info("[egg-Redis] 广告数据初始化完成");
}

async function redis_set_Notices(app) {
  // 获取所有有效的广告数据
  const notices = await app.model.Notice.findAll({
    where: { status: 1 } ,
    attributes:{exclude:['updated_at','status']},
    order:[['sort','ASC'],['created_at','DESC']]
  });

  await app.redis.set("notices_list", JSON.stringify(notices));
}

async function redis_set_article(app) {
  // 获取所有启用状态的文章数据
  const articles = await app.model.Article.findAll({
    where: { status: 1 },
    attributes:['content','type','created_at'],
    order:[['created_at','DESC']]
  });

  // 将每篇文章单独存储,方便单个查询
  for (const article of articles) {
    await app.redis.set(`article_${article.type}`, JSON.stringify(article));
  }
  app.logger.info("[egg-Redis] 文章数据初始化完成");
}

async function redis_set_dict_list(app) {
  // 获取所有字典数据
  const dictionaries = await app.model.Dictionary.findAll();
  const obj = {};
  // 遍历每个字典
  for (const dict of dictionaries) {
    // 获取该字典下的所有详情数据
    obj[dict.dict_key] = await app.model.DictionaryDetail.findAll({
      where: {
        parent_id: dict.id,
      },
      attributes:['id','dict_key','dict_value'],
      order:[['sort','ASC'],['created_at','DESC']]
    });
  }
  // 将字典详情数据存入Redis
  await app.redis.set(`dict_list`, JSON.stringify(obj));
  app.logger.info("[egg-Redis] 字典数据初始化完成");
}

async function redis_set_position_list(app) {
  redis_set_all_position_list(app)
  const where = {}
  // 只查询顶级岗位
  where.parent_id = null;
  where.status = 1;
  let list = await app.model.Position.findAll({
    where,
    attributes:['id','name'],
    include: [
      {
        where:{status:1},
        model: app.model.Position,
        as: 'children',
        attributes:['id','name'],
        include: [
          {
            attributes:['id','name'],
            model: app.model.Position,
            as: 'children'
          }
        ]
      }
    ],
    order: [
      ['sort', 'ASC'],
      ['created_at', 'DESC'],
      [{ model: app.model.Position, where:{status:1}, as: 'children',attributes:['id','name'], }, 'sort', 'ASC'],
      [{ model: app.model.Position, where:{status:1}, as: 'children',attributes:['id','name'], }, { where:{status:1}, model: app.model.Position, as: 'children',attributes:['id','name'], }, 'sort', 'ASC']
    ]
  });
  await app.redis.set(`position_list`, JSON.stringify(list));
  app.logger.info("[egg-Redis] 岗位数据初始化完成");
}
async function redis_set_all_position_list(app) {
  const where = {}
  // 只查询顶级岗位
  where.parent_id = null;
  let list = await app.model.Position.findAll({
    where:{status:1},
    attributes:['id','name','parent_id'],
    order: [
      ['sort', 'ASC'],
      ['created_at', 'DESC']
    ]
  });
  await app.redis.set(`all_position_list`, JSON.stringify(list));
  app.logger.info("[egg-Redis] 全部岗位数据初始化完成");
}

async function init(app) {
  await user_init(app);
  await dict_init(app);
  redis_set_ads(app);
  redis_set_Notices(app);
  redis_set_dict_list(app);
  redis_set_article(app);
  redis_set_position_list(app);
}
module.exports = { init, dict_arr,redis_set_ads, redis_set_dict_list, redis_set_position_list, redis_set_Notices,redis_set_article};
